package com.coin.exchange.okcoin.rest;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

/**
 * 
 * @author duyuchong
 *
 */
public class HttpUtil {
	
	private static HttpHeaders getHttpHeaders() {
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		return headers;
	}

	private static RestTemplate getRestTemplate() {
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
		StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
		messageConverters.add(converter);
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.setMessageConverters(messageConverters);
		return restTemplate;
	}

	public static String get(String url, Map<String, Object> params) throws Exception {
		RestTemplate restTemplate = getRestTemplate();
		if (params != null && !params.isEmpty()) {
			url += "?";
			for (String key : params.keySet()) {
				url += key + "=" + params.get(key) + "&";
			}
//			url += "sign=";
			url = url.substring(0, url.length() - 1);
		}
		String result = restTemplate.getForObject(url, String.class);
		return result;
	}

	public static String post(String url, String body) throws Exception {
		RestTemplate restTemplate = getRestTemplate();
		HttpHeaders headers = getHttpHeaders();
		HttpEntity<String> formEntity = new HttpEntity<String>(body, headers);
		String result = restTemplate.postForObject(url, formEntity, String.class);
		return result;
	}
	
}
